const { observable, action } = require('mobx-miniprogram');
const cloudHelper = require('../../../helpers/cloud_helper.js');
const pageHelper = require('../../../helpers/page_helper.js');
const dayjs = require('dayjs');

// 反馈模块Store
export const feedbackStore = observable({
  // 反馈列表数据
  feedbackList: [],
  
  // 当前选中的反馈
  currentFeedback: null,
  
  // 反馈类型列表
  feedbackTypes: [],
  
  // 反馈过滤条件
  filter: {
    type: '',
    status: '',
    priority: '',
    sortBy: 'createTime',
    sortOrder: 'desc',
    searchKey: '',
    dateRange: null
  },
  
  // 反馈统计数据
  statistics: {
    total: 0,
    pending: 0,
    processing: 0,
    resolved: 0,
    byType: {},
    byPriority: {}
  },
  
  // 页面加载状态
  loading: false,
  
  // 计算属性：筛选后的反馈列表
  get filteredFeedbacks() {
    if (!this.feedbackList.length) return [];
    
    let filtered = [...this.feedbackList];
    
    // 根据类型筛选
    if (this.filter.type) {
      filtered = filtered.filter(f => f.type === this.filter.type);
    }
    
    // 根据状态筛选
    if (this.filter.status) {
      filtered = filtered.filter(f => f.status === this.filter.status);
    }
    
    // 根据优先级筛选
    if (this.filter.priority) {
      filtered = filtered.filter(f => f.priority === this.filter.priority);
    }
    
    // 根据日期范围筛选
    if (this.filter.dateRange && this.filter.dateRange.start && this.filter.dateRange.end) {
      const startDate = dayjs(this.filter.dateRange.start).startOf('day');
      const endDate = dayjs(this.filter.dateRange.end).endOf('day');
      
      filtered = filtered.filter(f => {
        const createTime = dayjs(f.createTime);
        return createTime.isAfter(startDate) || createTime.isSame(startDate) && 
               (createTime.isBefore(endDate) || createTime.isSame(endDate));
      });
    }
    
    // 根据关键词搜索
    if (this.filter.searchKey) {
      const key = this.filter.searchKey.toLowerCase();
      filtered = filtered.filter(f => 
        f.title.toLowerCase().includes(key) || 
        f.content.toLowerCase().includes(key) ||
        f.submitterName.toLowerCase().includes(key)
      );
    }
    
    // 排序
    filtered.sort((a, b) => {
      const field = this.filter.sortBy;
      const order = this.filter.sortOrder === 'asc' ? 1 : -1;
      
      if (field === 'createTime' || field === 'updateTime') {
        const dateA = dayjs(a[field]);
        const dateB = dayjs(b[field]);
        return dateA.isAfter(dateB) ? order : -order;
      }
      
      return a[field] > b[field] ? order : -order;
    });
    
    return filtered;
  },
  
  // 计算属性：获取未处理的紧急反馈
  get urgentFeedbacks() {
    return this.feedbackList.filter(f => 
      f.priority === 'high' && 
      (f.status === 'pending' || f.status === 'processing')
    );
  },
  
  // Action: 设置反馈列表
  setFeedbackList: action(function(feedbacks) {
    this.feedbackList = feedbacks;
    this.updateStatistics();
  }),
  
  // Action: 更新统计数据
  updateStatistics: action(function() {
    // 基础统计
    const byType = {};
    const byPriority = {};
    
    // 初始化统计数据
    this.feedbackTypes.forEach(type => {
      byType[type.id] = 0;
    });
    
    ['low', 'medium', 'high'].forEach(priority => {
      byPriority[priority] = 0;
    });
    
    // 统计各类型和优先级的数量
    this.feedbackList.forEach(feedback => {
      if (byType[feedback.type] !== undefined) {
        byType[feedback.type]++;
      }
      
      if (byPriority[feedback.priority] !== undefined) {
        byPriority[feedback.priority]++;
      }
    });
    
    this.statistics = {
      total: this.feedbackList.length,
      pending: this.feedbackList.filter(f => f.status === 'pending').length,
      processing: this.feedbackList.filter(f => f.status === 'processing').length,
      resolved: this.feedbackList.filter(f => f.status === 'resolved').length,
      byType,
      byPriority
    };
  }),
  
  // Action: 设置当前反馈
  setCurrentFeedback: action(function(feedbackId) {
    this.currentFeedback = this.feedbackList.find(f => f._id === feedbackId) || null;
  }),
  
  // Action: 添加反馈
  addFeedback: action(function(feedback) {
    // 准备提交到云端的数据
    const data = {
      type: feedback.type,
      content: feedback.content,
      mediaList: feedback.mediaList || []
    };
    
    // 返回一个Promise，以便页面可以知道提交状态
    return new Promise((resolve, reject) => {
      // 调用云函数提交反馈
      cloudHelper.callCloud('feedback/add', data, { hint: false })
        .then(result => {
          // 将返回的数据添加到本地列表
          const newFeedback = result.data;
          this.feedbackList.unshift(newFeedback);
          this.updateStatistics();
          resolve(newFeedback);
        })
        .catch(err => {
          console.error('提交反馈失败', err);
          reject(err);
        });
    });
  }),
  
  // Action: 更新反馈
  updateFeedback: action(function(feedbackId, data) {
    const index = this.feedbackList.findIndex(f => f._id === feedbackId);
    if (index >= 0) {
      this.feedbackList[index] = {...this.feedbackList[index], ...data};
      
      // 如果当前选中的是这个反馈，也更新currentFeedback
      if (this.currentFeedback && this.currentFeedback._id === feedbackId) {
        this.currentFeedback = {...this.currentFeedback, ...data};
      }
      
      this.updateStatistics();
    }
  }),
  
  // Action: 删除反馈
  deleteFeedback: action(function(feedbackId) {
    const index = this.feedbackList.findIndex(f => f._id === feedbackId);
    if (index >= 0) {
      this.feedbackList.splice(index, 1);
      
      // 如果当前选中的是这个反馈，清空currentFeedback
      if (this.currentFeedback && this.currentFeedback._id === feedbackId) {
        this.currentFeedback = null;
      }
      
      this.updateStatistics();
    }
  }),
  
  // Action: 设置反馈类型列表
  setFeedbackTypes: action(function(types) {
    this.feedbackTypes = types;
  }),
  
  // Action: 设置过滤条件
  setFilter: action(function(filter) {
    this.filter = {...this.filter, ...filter};
  }),
  
  // Action: 清空过滤条件
  clearFilter: action(function() {
    this.filter = {
      type: '',
      status: '',
      priority: '',
      sortBy: 'createTime',
      sortOrder: 'desc',
      searchKey: '',
      dateRange: null
    };
  }),
  
  // Action: 设置加载状态
  setLoading: action(function(loading) {
    this.loading = loading;
  }),
  
  // Action: 加载反馈列表
  loadFeedbackList: action(function() {
    this.setLoading(true);
    
    return new Promise((resolve, reject) => {
      cloudHelper.callCloud('feedback/list', {}, { hint: false })
        .then(result => {
          this.setFeedbackList(result.data);
          resolve(result.data);
        })
        .catch(err => {
          console.error('加载反馈列表失败', err);
          reject(err);
        })
        .finally(() => {
          this.setLoading(false);
        });
    });
  })
}); 